package com.topvision.common.tree;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shengwm
 * @version V0.0.1
 * @Title: TreeUtil
 * @Package com.topvision.common.tree
 * @Description: 树形工具类
 * @date 2017/4/18 14:13
 */
public class TreeUtil {
    public static List<TreeNode> build(List<? extends StandardTree> list) {

        if (list != null) {
            int len = list.size();
            if (len > 0) {
                List<TreeNode> mainList = Lists.newArrayList();
                Map<String, TreeNode> map = Maps.newHashMap();
                for (StandardTree t : list) {
                    String id = t.getId();
                    String parentId = t.getParentId();
                    Object data = t.getData();
                    String text = t.getText();
                    Integer sort = t.getSort();
                    TreeNode treeNode = new TreeNode();
                    treeNode.setData(data);
                    treeNode.setId(id);
                    treeNode.setParentId(parentId);
                    treeNode.setText(text);
                    treeNode.setSort(sort);
                    if (parentId == null || "".equals(parentId) || ("0").equals(parentId)) {
                        mainList.add(treeNode);
                    }
                    map.put(id.toString(), treeNode);
                }
                Collection<TreeNode> values = map.values();
                List<TreeNode> sortValues = values.stream().sorted((c1, c2) -> c1.getParentId().compareTo(c2.getParentId())).sorted((t1, t2) -> t1.getSort().compareTo(t2.getSort())).collect(Collectors.toList());
                for (TreeNode t : sortValues) {
                    String parentId = t.getParentId();
                    if (parentId != null && !"".equals(parentId) && !("0").equals(parentId)) {
                        TreeNode parent = map.get(parentId.toString());
                        List<TreeNode> children = parent.getChildren();
                        if (children == null) {
                            children = Lists.newArrayList();
                            parent.setChildren(children);
                        }
                        children.add(t);
                    }
                }
                return mainList;
            }
        }
        return null;
    }
}
